#include <stdio.h>
#include <stdlib.h>
#include	<unistd.h>
#include <stdbool.h>
#include <string.h>
#include <signal.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "config_parser.h"
#include "tcp.h"

void validate_input_parameters(int argc, char * argv[]);
void terminate();
void clean_exit(int sig);
void lead(int num_proposers);
void enable_signal_handler();

int self_id, num_proposers;
//------------------------------------------------------------------------------
int main(int argc, char *argv[]) {
	enable_signal_handler();
	num_proposers = -1;
	validate_input_parameters(argc, argv);
	printf("parsed\n");
	parse_config_file(self_id, config_file, 1, num_proposers);
	lead(num_proposers);
	terminate();
	return 1;
}

void terminate() {
	sleep(5);
	close_sockets(get_config_info());
	free(get_config_info());
}
void validate_input_parameters(int argc, char * argv[]) {

	if (argc != 4) {
		fprintf(stdout, "Incompatible call to this program. Try Again.!\n");
		fprintf(stdout, "<1. Leader ID>\n"
			"<2. Number of proposers (at least one.)>\n"
			"<3. Configuration File>\n");
		exit(-1);
	} else {
		self_id = atoi(argv[1]);
		num_proposers = atoi(argv[2]);
		config_file = argv[3];
	}

}
void clean_exit(int sig) {

	signal(sig, clean_exit);
	terminate();
	exit(0);

}
void lead(int num_proposers) {

	char yes;
	char no;
	yes = 'y';
	no = 'n';
	int i;

	for (i = 0; i < num_proposers; i++)
		send(get_config_info()->l.sid[i], &yes, sizeof(char), 0);

	printf("num_prop: %d num_node: %d\n", num_proposers, get_config_info()->num_nodes);

	for (i = num_proposers; i < get_config_info()->num_nodes; i++) {
		int status = send(get_config_info()->l.sid[i], &no, sizeof(char), 0);
		printf("%d\n", status);
	}

}
void enable_signal_handler() {
	signal(SIGINT, clean_exit);
	signal(SIGKILL, clean_exit);
	signal(SIGABRT, clean_exit);
	signal(SIGALRM, clean_exit);
	signal(SIGBUS, clean_exit);
	signal(SIGCHLD, clean_exit);
	signal(SIGCONT, clean_exit);
	signal(SIGFPE, clean_exit);
	signal(SIGHUP, clean_exit);
	signal(SIGILL, clean_exit);
	signal(SIGPIPE, clean_exit);
	signal(SIGQUIT, clean_exit);
	signal(SIGSEGV, clean_exit);
	signal(SIGSTOP, clean_exit);
	signal(SIGTERM, clean_exit);
	signal(SIGTSTP, clean_exit);
	signal(SIGTTIN, clean_exit);
	signal(SIGTTOU, clean_exit);
	signal(SIGUSR1, clean_exit);
	signal(SIGUSR2, clean_exit);
	signal(SIGPROF, clean_exit);
	signal(SIGSYS, clean_exit);
	signal(SIGTRAP, clean_exit);
	signal(SIGURG, clean_exit);
	signal(SIGVTALRM, clean_exit);
	signal(SIGXCPU, clean_exit);
	signal(SIGXFSZ, clean_exit);

}
